/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.variable.impl;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.variable.BackCache;
import com.je.meta.cache.variable.FrontCache;
import com.je.meta.service.variable.MetaSysVariablesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MetaSysVariablesServiceImpl implements MetaSysVariablesService {

    /**
     * 前端类型
     */
    public static final String FRONT_TYPE = "FRONT";
    /**
     * 公共类型
     */
    public static final String SHARE_TYPE = "SHARE";
    /**
     * 后端类型
     */
    public static final String BACK_TYPE = "BACK";

    @Autowired
    private BackCache backCache;
    @Autowired
    private FrontCache frontCache;
    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;

    /**
     * 加载用户变量
     */
    @Override
    public void reloadSystemVariables() {
        frontCache.clear();
        backCache.clear();
        List<DynaBean> lists = metaService.select("JE_CORE_CONFIG", ConditionsWrapper.builder().eq("CONFIG_ENABLED", "1"));
        Map<String, String> frontVars = new HashMap<>();
        Map<String, String> backVars = new HashMap<>();
        for (DynaBean var : lists) {
            if (SHARE_TYPE.equals(var.getStr("CONFIG_TYPE_CODE"))) {
                frontVars.put(var.getStr("CONFIG_CODE"), var.getStr("CONFIG_VALUE"));
                backVars.put(var.getStr("CONFIG_CODE"), var.getStr("CONFIG_VALUE"));
            } else if (FRONT_TYPE.equals(var.getStr("CONFIG_TYPE_CODE"))) {
                frontVars.put(var.getStr("CONFIG_CODE"), var.getStr("CONFIG_VALUE"));
            } else if (BACK_TYPE.equals(var.getStr("CONFIG_TYPE_CODE"))) {
                backVars.put(var.getStr("CONFIG_CODE"), var.getStr("CONFIG_VALUE"));
            }
        }

        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (Strings.isNullOrEmpty(currentTenantId)) {
            frontCache.putMapCache(frontVars);
            backCache.putMapCache(backVars);
        } else {
            frontCache.putMapCache(currentTenantId, frontVars);
            backCache.putMapCache(currentTenantId, backVars);
        }

    }

    @Override
    public Map<String, String> findNativeAllFrontVariables() {
        List<DynaBean> lists = metaService.select("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .eq("CONFIG_ENABLED", "1")
                .eq("CONFIG_TYPE_CODE", FRONT_TYPE));
        Map<String, String> frontVars = new HashMap<>();
        for (DynaBean var : lists) {
            frontVars.put(var.getStr("CONFIG_CODE"), var.getStr("CONFIG_VALUE"));
        }
        return frontVars;
    }

    @Override
    public Map<String, String> findNativeAllBackVariables() {
        List<DynaBean> lists = metaService.select("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .eq("CONFIG_ENABLED", "1")
                .eq("CONFIG_TYPE_CODE", BACK_TYPE));
        Map<String, String> backVars = new HashMap<>();
        for (DynaBean var : lists) {
            backVars.put(var.getStr("CONFIG_CODE"), var.getStr("CONFIG_VALUE"));
        }
        return backVars;
    }

    @Override
    public String findNativeBackVariable(String code) {
        DynaBean variableBean = metaService.selectOne("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .eq("CONFIG_ENABLED", "1")
                .eq("CONFIG_TYPE_CODE", BACK_TYPE)
                .eq("CONFIG_CODE", code));
        if (variableBean == null) {
            return null;
        }
        return variableBean.getStr("CONFIG_CODE");
    }

    @Override
    public String findNativeFrontVariable(String code) {
        DynaBean variableBean = metaService.selectOne("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .eq("CONFIG_ENABLED", "1")
                .eq("CONFIG_TYPE_CODE", FRONT_TYPE)
                .eq("CONFIG_CODE", code));
        if (variableBean == null) {
            return null;
        }
        return variableBean.getStr("CONFIG_CODE");
    }

    /**
     * 根据Code获取系统变量
     *
     * @param code
     * @return
     */
    @Override
    public String findNativeSystemVariable(String code) {
        DynaBean variableBean = metaService.selectOne("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .eq("CONFIG_ENABLED", "1")
                .eq("CONFIG_CODE", code));
        if (variableBean == null) {
            return null;
        }
        return variableBean.getStr("CONFIG_CODE");
    }

    @Override
    public void writeBackVariable(String key, String value) {
        DynaBean variableBean = metaService.selectOne("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .eq("CONFIG_ENABLED", "1")
                .eq("CONFIG_TYPE_CODE", BACK_TYPE)
                .eq("CONFIG_CODE", key));
        if (variableBean == null) {
            variableBean = new DynaBean("JE_CORE_CONFIG", false);
            variableBean.set("CONFIG_ENABLED", "1");
            variableBean.set("CONFIG_TYPE_CODE", BACK_TYPE);
            variableBean.set("CONFIG_CODE", key);
            variableBean.set("CONFIG_VALUE", value);
            commonService.buildModelCreateInfo(variableBean);
            metaService.insert(variableBean);
        } else {
            variableBean.set("CONFIG_VALUE", value);
            commonService.buildModelModifyInfo(variableBean);
            metaService.update(variableBean);
        }
    }

    @Override
    public void writeFrontVariable(String key, String value) {
        DynaBean variableBean = metaService.selectOne("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .eq("CONFIG_ENABLED", "1")
                .eq("CONFIG_TYPE_CODE", FRONT_TYPE)
                .eq("CONFIG_CODE", key));
        if (variableBean == null) {
            variableBean = new DynaBean("JE_CORE_CONFIG", false);
            variableBean.set("CONFIG_ENABLED", "1");
            variableBean.set("CONFIG_TYPE_CODE", FRONT_TYPE);
            variableBean.set("CONFIG_CODE", key);
            variableBean.set("CONFIG_VALUE", value);
            commonService.buildModelCreateInfo(variableBean);
            metaService.insert(variableBean);
        } else {
            variableBean.set("CONFIG_VALUE", value);
            commonService.buildModelModifyInfo(variableBean);
            metaService.update(variableBean);
        }
    }


}
